//
//  JZH ContactsViewController.m
//  极致荟
//
//  Created by hetao on 14-5-10.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHContactsViewController.h"
#import "JZHPaiXu.h"
#import "JZHDetailsViewController.h"
#import "OtherUsers.h"
#import "OtherUsersDao.h"
#import "JZHChatViewController.h"
@interface JZHContactsViewController ()
{
    NSMutableArray *name;
    JZHPaiXu *paixu;
    NSMutableArray *dataarr;
    
}
@end

@implementation JZHContactsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (id)initIsPusNote:(id)recmmde farr:(NSMutableArray *)farr
{
    JZHContactsViewController *jzh=[[JZHContactsViewController alloc] init];
    jzh.recmmde=recmmde;
    jzh.mfarr=farr;
    
    return jzh;
}

- (id)initIsSelectNote:(JZHChatViewController *)jzh
{
     JZHContactsViewController *jzh1=[[JZHContactsViewController alloc] init];
        jzh1.chatView=jzh;
    return jzh1;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self dbFriend];
   
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    dataarr=[[NSMutableArray alloc]init];
    name=[[ NSMutableArray alloc]init];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self httpLoadDatas];
    });
    
    
    if(OSVersionIsAtLeastiOS7>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 12, 20)];
    [leftButton addTarget:self action:@selector(leftDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    self.navigationItem.title=@"通讯录";

}

- (void)leftDrawerButtonPress:(UIButton *)but
{
    [UINavigationController Pop:self];
}


- (void)httpLoadDatas
{
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:[User defuceUser].userId],@"userId",@"1",@"friendType", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"friends/friendsList") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==0)
        {
            NSLog(@"%@",data);
            [dataarr removeAllObjects];
            for(NSDictionary *datadic in [[data objectForKey:@"data"] objectForKey:@"list"])
            {
                OtherUsers *ouser=[[OtherUsers alloc]init];
                ouser.userId=[[datadic objectForKey:@"userId"] intValue];
                ouser.userHeadImage=[[[data objectForKey:@"data"] objectForKey:@"imgPrefix"] stringByAppendingString:[datadic objectForKey:@"userAvatar"]];
                if([NSNull null]==[datadic objectForKey:@"userName"])
                {
                    ouser.name=@"暂无";
                }else
                {
                  ouser.name=[datadic objectForKey:@"userName"];
                   
                }
                if([NSNull null]==[datadic objectForKey:@"remark"]  )
                {
                    ouser.bname=@"";
                }else
                {
                    
                    ouser.bname=[datadic objectForKey:@"remark"];
                    NSLog(@"%@",ouser.bname);
                }
                if([[datadic objectForKey:@"asterisk"] intValue]==1)
                {
                    ouser.isAs=YES;
                }else
                {
                    ouser.isAs=NO;
                }
                
                [OtherUsersDao insertData:ouser];
                [dataarr addObject:ouser];
            }
            
            
            paixu=[JZHPaiXu shareArr:dataarr];
            [self.table reloadData];
        }
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark ---tableview代理---
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [(NSMutableArray *)[paixu.pingyinDic objectForKey:paixu.pingyin[section]] count];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return paixu.pingyin.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return paixu.pingyin[section] ;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str=@"pinyin";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:str];
    if(!cell)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        cell=[self addViewCell:cell];
    }
    return [self addcellData:cell indexpath:indexPath table:tableView];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     OtherUsers *ouser=(OtherUsers *)[(NSMutableArray *)[paixu.pingyinDic objectForKey:paixu.pingyin[indexPath.section]] objectAtIndex:indexPath.row];
   
    if(self.recmmde!=nil && [self.recmmde isKindOfClass:[OtherUsers class]])
    {
         [self.navigationController pushViewController:[[JZHChatViewController alloc]initOuser:ouser Recommend:self.recmmde]  animated:YES];
    }
    
    if(self.mfarr)
    {
         [self selectList:[tableView cellForRowAtIndexPath:indexPath] otuser:ouser isEnden:YES index:indexPath];
       
    }
    
    if(self.chatView)
    {
        self.chatView.recommend=ouser;
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        
        [self.navigationController pushViewController:[[JZHDetailsViewController alloc]initOthUser:ouser] animated:YES];
    }
    
   
   
}

///向Cell添加控件

- (UITableViewCell *)addViewCell:(UITableViewCell *)cell
{
    UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(14, 10, 40, 40)];
    [image.layer setCornerRadius:6 ];
    [image.layer setMasksToBounds:YES];
    [cell.contentView addSubview:image];
    image.tag=2221;
    
   
    
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(70, 16, 200, 21)];
    [lable setFont:[UIFont systemFontOfSize:14]];
    lable.tag=2222;
    [cell.contentView addSubview:lable];
    
    UIImageView * selectimage=[[UIImageView alloc]initWithFrame:CGRectMake(290,15, 20, 20)];
    [selectimage setImage:[UIImage imageNamed:@"fgou"]];
    selectimage.tag=2223;
    selectimage.hidden=YES;
    [cell.contentView addSubview:selectimage];
    
    return cell;
}
- (UITableViewCell *)addcellData:(UITableViewCell *)cell indexpath:(NSIndexPath *)index table:(UITableView *)table
{
    UILabel *label=(UILabel *)[cell.contentView viewWithTag:2222];
    OtherUsers *ouser=(OtherUsers *)[(NSMutableArray *)[paixu.pingyinDic objectForKey:paixu.pingyin[index.section]] objectAtIndex:index.row];
    if(ouser.bname.length!=0)
    {
        label.text=ouser.bname;
    }else
    {
        [label setText:[ouser name]];
    }
    
    [self selectList:cell otuser:ouser isEnden:NO index:index];
    UIImageView *image=(UIImageView *)[cell.contentView  viewWithTag:2221];
    [ImageCache imageUrl:ouser.userHeadImage UiImageview:image];
    
    return cell;
}

//选择多个联系人
- (void)selectList:(UITableViewCell *)cell otuser:(OtherUsers *)ouser isEnden:(BOOL)isen index:(NSIndexPath *)index
{
    if(!self.mfarr)
    {
        return;
    }
  
    UIImageView *image=(UIImageView *)[cell.contentView  viewWithTag:2223];
    if(isen)
    {
        OtherUsers *ouser=(OtherUsers *)[(NSMutableArray *)[paixu.pingyinDic objectForKey:paixu.pingyin[index.section]] objectAtIndex:index.row];
        for(OtherUsers *ou in self.mfarr)
        {
            if(ouser.userId==ou.userId)
            {
                [self.mfarr removeObject:ouser];
                image.hidden=YES;
                return;
            }
        }
        
        [self.mfarr addObject:ouser];
        
        image.hidden=NO;
      
    }else
    {
        OtherUsers *ouser=(OtherUsers *)[(NSMutableArray *)[paixu.pingyinDic objectForKey:paixu.pingyin[index.section]] objectAtIndex:index.row];
        for(OtherUsers *ou in self.mfarr)
        {
            if(ouser.userId==ou.userId)
            {
                image.hidden=NO;
                return;
            }
        }
        image.hidden=YES;
    }
    
    
}
///加载本地数据库中的数据
- (void)dbFriend
{
    dataarr =[OtherUsersDao selectData];
    paixu=[JZHPaiXu shareArr:dataarr];
    [self.table reloadData];
}
@end
